<template>
  <PageWrapper contentFullHeight fixedHeight contentClass="main-box">
    <CommonDateSearch v-if="initLocationData" ref="searchRef" @search="handleSearch" :extraSearch="extraSearch">
    </CommonDateSearch>
    <div class="content-box">
      <div class="chart-box">
        <Line class="chart" :loading="loadingRef"  :chartData="chartData" title="PCW-平均值" />
      </div>
      <a-card class="common-card flex table-box" title="PCW">
        <BasicTable @register="registerTable">
          <template #toolbar>
            <!-- <a-button type="primary" @click="handleDownload" :loading="uploadLoading">导出</a-button> -->
          </template>
        </BasicTable>

      </a-card>
    </div>
  </PageWrapper>
</template>
<script setup>
import Line from '@/components/Charts/Line/index.vue'
import { ref, onMounted, reactive } from 'vue'
import { PageWrapper } from '@/components/Page'
import CommonDateSearch from '@/components/CommonDateSearch/index.vue'
import Icon from '@/components/Icon/Icon.vue'
import { chartChildLisExport, getChartChildRealTimeData, getChildRealTimeDataAndSon } from '@/api/common/chart'
import { BasicTable, useTable } from '@/components/Table'
import { getDictListByCode } from '@/api/sys/dict'
import { message } from 'ant-design-vue'

defineOptions({ name: 'exhaustEmissions' })
const dictCode = 'air_pcw_systems'
const searchRef = ref()
const searchInfo = reactive({
  dictCode,
})
const loadingRef = ref(true)
const chartData = ref()
const locationRef = ref([])
const initLocationData = ref(false)
const uploadLoading = ref(false)
const extraSearch = ref([
  {
    field: 'itemName',
    label: '位置选择',
    component: 'Select',
    colProps: { span: 6 },
    componentProps: ({ formModel }) => {
      formModel.itemName = locationRef.value[0].itemName
      return {
        options: locationRef.value,
        fieldNames: {
          label: 'itemName',
          value: 'itemName',
        }
      }
    },
  },
])
const [registerTable, { setLoading, setColumns, setTableData }] = useTable({//setTableData控制右上角的数据选择
  rowKey: 'id',
  columns: [],
  pagination: false,
  formConfig: {
    labelWidth: 120,
  },
  bordered: true,
  striped: false,
})
const customOptions = (options) => {
  let arr = []
  console.log(options, 'options')
  options.forEach(item => {
    if (!arr.find(_item => item.label.indexOf(_item.label) > -1)) {
      arr.push({
        label: item.label.substr(0, item.label.length - 3),
        value: item.label.substr(0, item.label.length - 3)
      })
    }
  })
  return arr
}
onMounted(async () => {
  await getLocationData()
  // searchRef.value.handleSearch()
})
const getLocationData = async () => {
  const dictData = await getDictListByCode(dictCode)
  extraSearch.value[0].defaultValue = dictData[0]?.itemName
  locationRef.value = dictData
  initLocationData.value = true
}

const handleSearch = (params) => {
  Object.assign(searchInfo, params)
  getData()
}

const formatHeader = (headerData) => {
  const headerList = headerData.map((item) => ({
    title: item,
    dataIndex: item,
    width: 100,
    customRender: ({ text }) => {
      return text || '--'
    },
  }))
  headerList.unshift({
    title: '数据名称',
    dataIndex: 'name',
    width: 250,
    fixed: 'left',
    merge: true,
  })

  setColumns(headerList)
}

const formatTableData = (tableData) => {
  const { xaxisList, yaxisList, allyAxisList } = tableData
  const data = allyAxisList.map((item) => {
    const { data, ...others } = item
    const record = { ...others }
    data.forEach((item, index) => {
      record[xaxisList[index]] = item
    })
    return record
  })
  console.log(data,"???");
  
  setTableData(data)
}

const getData = () => {
  loadingRef.value = true
  getChildRealTimeDataAndSon({ ...searchInfo })
    .then((res) => {
      console.log(res, "asdw");

      chartData.value = res
      formatTableData(res)
      formatHeader(res.xaxisList)
    })
    .finally(() => {
      loadingRef.value = false
    })
}

const download = (res, name) => {
  var blob = new Blob([res])
  var href = URL.createObjectURL(blob)
  var downloadElement = document.createElement('a')
  downloadElement.href = href
  downloadElement.download = name
  document.body.appendChild(downloadElement)
  downloadElement.click()
  document.body.removeChild(downloadElement)
  URL.revokeObjectURL(href)
}
const handleDownload = async () => {
  uploadLoading.value = true
  chartChildLisExport({ ...searchInfo }).then(res => {
    const { data, headers } = res
    let contentDisposition = decodeURIComponent(headers["content-disposition"]);
    const filenameMatch = contentDisposition.match(/filename\*=UTF-8''(.+)|filename="(.+)"|filename=(.+)/)
    const fileName = filenameMatch[1] || filenameMatch[2] || filenameMatch[3]
    download(data, fileName);
    message.success("导出成功");
  }).finally(() => {
    uploadLoading.value = false
  })

}
</script>
<style scoped lang="scss">
.content-box {
  display: flex;
  flex: 1;
  flex-direction: column;
  background: #fff;
  overflow: hidden;
  .chart-box {
    padding: 8px 8px 4px;
  }

  .chart-box,
  .table-box {
    flex: 1;
    flex-shrink: 0;
    overflow: hidden;
  }

  :deep(.ant-table-wrapper) {
    padding: 0;
  }
}
</style>
